package wickethub.web.page;

import org.apache.wicket.PageParameters;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.StringResourceModel;

import wickethub.data.Util;
import wickethub.domain.BlogPost;
import wickethub.domain.Resource;
import wickethub.domain.Snippet;
import wickethub.repository.ResourceRepository;
import wickethub.web.app.EntityDetachableModel;
import wickethub.web.components.ResourceIconImage;
import wickethub.web.components.UnknownLabel;

import com.google.inject.Inject;

public class ViewResourcePage extends BasePage {

	@Inject	private ResourceRepository repo;
	
	public ViewResourcePage(PageParameters params) {

		final IModel<Resource> resourceModel = new EntityDetachableModel<Resource>(repo.getById(params.getLong("1")), repo);
		final Resource resource = resourceModel.getObject();
		
		final FeedbackPanel feedback = new FeedbackPanel("feedback");
		add(feedback);
		
		setTitle(new StringResourceModel("view.page.title", this, resourceModel));
		
		add(new ResourceIconImage("image", resourceModel));
		
    	add(new Label("moduleTitle", resource.getTitle()));
		
    	add(new Label("description", resource.getDescription()) {
			@Override
			public boolean isVisible() {
				return resource.getDescription() != null;
			}
		});
		
		add(new Label("votes", resource.getTimesRated().toString()));
		add(new Label("rating", String.format("%.2f", resource.getRating())));
		
		add(Util.getRatingPanel("stars", resourceModel, repo));
		
		add(new Label("author", resource.getAuthor()) {
			@Override
			public boolean isVisible() {
				return resource.getAuthor() != null;
			}
		});
		
		add(new Link<Resource>("edit", resourceModel) {
			@Override
			public void onClick() {
				setResponsePage(new EditResourcePage(getModel()));
			}
		});
		
		String t = resource.getTopics();
		add(new UnknownLabel("tags", t));
		
		String v = resource.getVersions();
		add(new UnknownLabel("versions", v));
		
		add(getResourcePanel("panel", resourceModel));
		
	}
	
	@SuppressWarnings("unchecked") // FIXME this smells
	private Panel getResourcePanel(String panelId, IModel<Resource> model) {
		
		if (Snippet.class.isAssignableFrom(model.getObject().getClass())) {
			return new ViewSnippetPanel(panelId, (IModel) model);
		} else if (BlogPost.class.isAssignableFrom(model.getObject().getClass())) {
			return new ViewBlogPostPanel(panelId, (IModel) model);
		} else { // for other resource, default Component
			return new ViewComponentPanel(panelId, (IModel) model);
		}
		
	}


}